package com.yuerenjf.yuerenjinfu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.os.Environment;
import android.os.Build;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import android.net.Uri;
import android.webkit.ValueCallback;
import android.provider.MediaStore;
import android.database.Cursor;
import android.app.Activity;
import android.content.ClipData;
import android.annotation.TargetApi;

import java.io.File;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;
import com.yuerenjf.yuerenjinfu.utils.FileUtils;

import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.analytics.MobclickAgent;
import com.yuerenjf.yuerenjinfu.widget.X5WebView;


import org.xutils.common.util.LogUtil;


public class WebActivity extends BaseActivity implements View.OnClickListener {

    private String urlAll;

    private X5WebView webView;
    //    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    // 这个路径是用户选择图片以后进行压缩的压缩路径
    private String compressPath = "";
    // 这个变量的作用在使用小米手机点击选择图片的时候,使用到的
    private android.webkit.ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;

    public static void launchActivity(Context context, String url) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ll_back.setOnClickListener(this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.i("onNewIntent");
        setIntent(intent);
        urlAll = getIntent().getStringExtra("url");

        String web_signature = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_WEB_SIGNATURE);
        String token = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_TOKEN);
        urlAll = urlAll + "?access_token=" + token + "&signature=" + web_signature;
        LogUtil.i(urlAll);
        webView.loadUrl("");
    }



    @Override
    protected View getChildView() {
        View view = View.inflate(WebActivity.this, R.layout.activity_web, null);
        webView = (X5WebView) view.findViewById(R.id.webview);

        urlAll = getIntent().getStringExtra("url");
        Log.e("WebActivity", "url----------" + urlAll);
//        urlAll="https://www.zpjinfu.com/";
        webView.requestFocusFromTouch();
//        MobSDK.init(WebActivity.this);
        CookieSyncManager cookieSyncMngr =
                CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();

        WebSettings webSettings = webView.getSettings();
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua + ";" + Constants.HEAD_REQUEST);
        LogUtil.i(ua + ";" + Constants.HEAD_REQUEST);
        webSettings.setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.e("WebActivity", "currentUrl1111--------" + url);
                //gsf:取消URL拦截，所有的都在webview中打开
//                Intent intent = new Intent();
//                if (url.equals(ConstantUtils.HOST)) {
//                    intent.putExtra("tab", 0);
//                    intent.setClass(WebActivity.this, MainActivity.class);
//                    startActivity(intent);
//                }

                view.loadUrl(url);
                return false;
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                LogUtil.i("onPageFinshed:"+s);
//                    String js="var btn1 = document.getElementById(\"uploadFileA\");\n" +
//                            "btn1.addEventListener(\"click\", function() {\n" +
//                            "    alert(\"为被点击了\");\n" +
//                            "});";

//                String js = "var script = document.createElement('script');";
//                js += "script.type = 'text/javascript';";
//                js += "var child=document.getElementsByTagName('a')[0];";
//                js += "child.onclick=function(){userIdClick();};";
//                js += "function userIdClick(){myObj.getClose();};";

//                    webView.loadUrl("javascript:" + "imageUpload('uploadFileA','previewA1')");

                String js=" var display=function (){\n" +
                        "            var path=document.getElementById(\"uploadFileA\").textContent;\n" +
                        "            document.getElementById(\"previewA1\").innerHTML(\"<b>\"+path+\"</b>\");\n" +
                        "        }";
                webView.loadUrl("javascript:" + js);


            }
        });


        webView.setWebChromeClient(webChromeClient);


        String web_signature = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_WEB_SIGNATURE);
        String token = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_TOKEN);


        urlAll = urlAll + "?access_token=" + token + "&signature=" + web_signature;

        LogUtil.i(urlAll);
        webView.loadUrl(urlAll);
//        webView.addJavascriptInterface(new JSInterface(this, rl_titlebar), "Android");
        webView.addJavascriptInterface(new MyJSInterface(), "Android");

        return view;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    rl_titlebar.setVisibility(View.GONE);
                    break;
                case 2:
                    rl_titlebar.setVisibility(View.VISIBLE);
                    break;

                case 3:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    }

                    String webUrl=msg.getData().getString("webUrl");
                    LoginActivity.launchLoginActivity(WebActivity.this, webUrl);
//                    rl_titlebar.setVisibility(View.VISIBLE);
                    break;

                case 4:
                    String position=msg.getData().getString("current");
                    Intent intent=new Intent(WebActivity.this, MainActivity.class);
                    intent.putExtra("current",position);
                    startActivity(intent);
                default:
                    break;
            }
        }
    };

    class MyJSInterface {

        //绑定银行卡页面隐藏title
        @JavascriptInterface
        public void hideTitle() {
            handler.sendEmptyMessage(1);
        }

        @Override
        public int hashCode() {
            return super.hashCode();
        }

        @JavascriptInterface
        public void showTitle() {
            handler.sendEmptyMessage(2);
        }

        @JavascriptInterface
        public void launchLogin(String webUrl) {
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("webUrl", webUrl);
            message.setData(bundle);
            message.what = 3;
            handler.sendMessage(message);
        }

        //ShareSDK
        @JavascriptInterface
        public void shareActivity(String title, String desc, String imageUrl, String loadUrl, final String
                momentsTitle) {
            UMImage umImage = new UMImage(WebActivity.this, imageUrl);
            UMWeb web = new UMWeb(loadUrl);
            web.setTitle(title);//标题
            web.setThumb(umImage);  //缩略图
            web.setDescription(desc);//描述

            new ShareAction(WebActivity.this)
                    .withMedia(web)
                    .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ)

                    .setCallback(shareListener).open();

        }

        @JavascriptInterface
        public void updateTab(String position){
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("current", position);
            message.setData(bundle);
            message.what = 4;
            handler.sendMessage(message);
        }
    }

    /*
    * 选择手机相册中的图片
    */
    private void chosePic() {
        FileUtils.delFile(compressPath);
        // "android.intent.action.GET_CONTENT"
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        innerIntent.addCategory(Intent.CATEGORY_OPENABLE);
        String IMAGE_UNSPECIFIED = "image/*";
        innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, "chose file");
        startActivityForResult(wrapperIntent, FILECHOOSER_RESULTCODE);
        compressPath = Environment.getExternalStorageDirectory().getPath() + "/uxian/temp";
        new File(compressPath).mkdirs();
        // File.separator是分隔符“/”或者“\”
        // 具体是那个，系统的不同，导致File.separator不同
        compressPath = compressPath + File.separator + "compress.jpg";
    }

    /**
     * 选择相册图片以后的操作
     *
     * @return
     */
    private Uri afterChosePic(Intent data) {
        // 获取图片的路径：
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
        if (cursor == null) {
            Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
            return null;
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        // 最后根据索引值获取图片路径
        String path = cursor.getString(column_index);
        if (path != null
                && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
            File newFile = FileUtils.compressFile(path, compressPath);
            return Uri.fromFile(newFile);
        } else {
            Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     * 当Android 5.0+以上系统调用修改用户头像的选择按钮, 在onActivityResutl中调用这个方法
     *
     * @param requestCode onActivityResult 中的 requestCode
     * @param resultCode  onActivityResult 中的resultCode
     * @param data        onActivityResult 中的data
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }

        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }


//        if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage && null == mUploadCallbackAboveL)
//                return;
//            Uri result = data == null || resultCode != RESULT_OK ? null : afterChosePic(data);
//            if (mUploadMessage != null) {
//                mUploadMessage.onReceiveValue(result);
//                mUploadMessage = null;
//            } else if (mUploadCallbackAboveL != null) {
//                onActivityResultAboveL(requestCode, resultCode, data);
//            }
//        }
        if (CacheUtils.getString(WebActivity.this, ConstantUtils.SP_SECRET).equals("")) {
            Log.e("WebActivity", "SP_SECRET---" + CacheUtils.getString(WebActivity.this, ConstantUtils.SP_SECRET));
            finish();
        }

//        if (requestCode == 0 && resultCode == RESULT_OK) {
//            urlAll = data.getExtras().getString("url");
//            if (urlAll == null) {
//                finish();
//            }
////            String token = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_TOKEN);
//            String token = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_TOKEN);
//            String web_signature = CacheUtils.getString(WebActivity.this, ConstantUtils.SP_WEB_SIGNATURE);
//            urlAll = urlAll + "?access_token=" + token + "&signature=" + web_signature;
//            webView.loadUrl(urlAll);
//        }
    }

    @Override
    public void onClick(View v) {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (rl_titlebar.getVisibility() == View.GONE) {
//                handler.sendEmptyMessage(2);
//            } else {
            if (webView.canGoBack()) {
                webView.goBack();//返回上一页面
                return true;
            } else {
                finish();
            }
//            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (this.webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }

    WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView webView, String s) {
            //gsf：如果来自不同域名，则显示导航栏
            String tmpUrl = webView.getUrl().toLowerCase();
            //Toast.makeText(WebActivity.this,tmpUrl,Toast.LENGTH_SHORT).show();
//            if (tmpUrl.indexOf(ConstantUtils.HOST) > -1) {
//                handler.sendEmptyMessage(1);
//            } else {
//                handler.sendEmptyMessage(2);
//            }
            super.onReceivedTitle(webView, s);
            if (s.length() > 8) {

                s = s.substring(0, 8) + "...";
            }
            tv_title.setText(s);
        }


        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            Log.i("test", "openFileChooser 1");
            uploadFile = uploadMsg;
            openFileChooseProcess();
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
            Log.i("test", "openFileChooser 2");
            uploadFile = uploadMsgs;
            openFileChooseProcess();
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            Log.i("test", "openFileChooser 3");
            uploadFile = uploadMsg;
            openFileChooseProcess();
        }

        // For Android  >= 5.0
        public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
            uploadFiles = filePathCallback;
            openFileChooseProcess();
            return true;
        }

    };

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(WebActivity.this, "分享成功", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(WebActivity.this, "分享失败", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(WebActivity.this, "分享取消", Toast.LENGTH_LONG).show();
        }
    };
}